package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.MonthCountMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.EmployeeLeaveExt;
import com.ruan.pojoExt.MonthCountExt;
import com.ruan.service.DepartmentService;
import com.ruan.service.MonthCountService;
import com.ruan.service.PositionService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/monthCount")
@CrossOrigin
@Slf4j

public class MonthCountController {

    @Resource
    private MonthCountService monthCountService;

    @Autowired
    private MonthCountMapper monthCountMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    PositionService positionService;

    @PostMapping("/getMonthCount/{currentPage}/{pageSize}")
    public Result getMonthCount(@PathVariable int currentPage,
                                @PathVariable int pageSize,
                                @RequestBody LTOQueryCondition LTOQueryCondition){//String month
        log.info("传来的搜索条件是：",LTOQueryCondition);
//        List<MonthCountExt> monthCountExtList = monthCountService.getMonthCount(String.valueOf(LTOQueryCondition.getMonth()));
        Date month = LTOQueryCondition.getMonth();
        // 使用SimpleDateFormat将Date对象转换为年月格式的字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String formattedMonth = sdf.format(month);
//        Page<MonthCount> iPage=new Page<>(currentPage,pageSize);
        Page<MonthCountExt> iPageExt=new Page<>(currentPage,pageSize);//封装

        LambdaQueryWrapper<MonthCount> queryWrapper = new LambdaQueryWrapper<>();
        //月份搜索//默认是上个月
        //可能格式不太对，稍微匹配一下得了
        queryWrapper.like(MonthCount::getMonth,formattedMonth);
        //员工模糊搜索
        LambdaQueryWrapper<Employee> employeeWrapper =new LambdaQueryWrapper<>();
        employeeWrapper.like(Employee::getName,LTOQueryCondition.getName());//模糊查询
        List<Employee> employeeList = employeeMapper.selectList(employeeWrapper);

        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
        queryWrapper.in(MonthCount::getEmployeeId, employeeIds);
        //部门搜索
        queryWrapper.eq(LTOQueryCondition.getDepartmentId()!=null,MonthCount::getDepartmentId, LTOQueryCondition.getDepartmentId());
        List<MonthCount> monthCountList = monthCountMapper.selectList(queryWrapper);



        List<MonthCountExt> monthCountExtList = new ArrayList<>();
        for(MonthCount monthCount : monthCountList){

            MonthCountExt monthCountExt = new MonthCountExt();

            Long employeeId = monthCount.getEmployeeId();
            Long departmentId = monthCount.getDepartmentId();

            Employee employee = employeeMapper.selectById(employeeId);
            Department department = departmentService.getById(departmentId);

            BeanUtils.copyProperties(monthCount,monthCountExt);
//            System.out.println("基础属性搬完了吗："+monthCountExt);
//            System.out.println("员工名是："+employee.getName());
            monthCountExt.setEmployeeName(employee.getName());
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                monthCountExt.setPosition(position.getPname());
            }

            monthCountExt.setPhone(employee.getPhone());
            monthCountExt.setDepartmentName(department.getName());

            monthCountExtList.add(monthCountExt);
        }
        //将monthCountExtList添加到iPageExt中
        iPageExt.setRecords(monthCountExtList);
        //设置iPageExt的总记录数为monthCountExtList的大小
        iPageExt.setTotal(monthCountExtList.size());
        if (iPageExt!=null){
            return new Result(Code.SELECT_OK,iPageExt);
        }
        return new Result(Code.SELECT_ERR,"查询失败！");
    }

    @GetMapping("/exportToExcel")
    public ResponseEntity<byte[]> exportToExcel(){
        try {
            byte[] excelBytes = monthCountService.exportToExcel();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "月统计表.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

   //获取个人上个月的绩效
    @PostMapping("/getSelfMonthCount/{currentPage}/{pageSize}")
    public Result getSelfMonthCount(@PathVariable int currentPage,
                                    @PathVariable int pageSize,
                                    @RequestBody QuerySelfAttendanceCondition querySelfAttendanceCondition){
        IPage<MonthCount> iPage = monthCountService.getSelfOnDuty(currentPage,pageSize, querySelfAttendanceCondition);

        if (iPage!=null){
            return new Result(Code.SELECT_OK,iPage);
        }
        return new Result(Code.SELECT_ERR,"查询个人月考勤数据失败！");
    }
}
